package com.lsh.netty.echo.mgspackecho;

import com.lsh.msgpack.MsgpackDecoder;
import com.lsh.msgpack.MsgpackEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021年04月12日17:18:40
 * @desc ：
 * //注意：巨坑1：使用MessagePack编解码框架 传输的Java对象 一定要加上org.msgpack.annotation.Message 注解@Message 才能 传输
 *
 */
public class EchoClient {

    private final String host;
    private final int port;
    private final int sendNumber;
    public EchoClient (String host,int port,int sendNumber ){
        this.host = host;
        this.port = port;
        this.sendNumber = sendNumber;
    }
    public void run() throws Exception{
        //配置Nio线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            /**
                             * 在消息头中新增报文长度字段，利用该字段进行半包的编解码
                             * 下面利用了Netty 提供的LengthFieldPrepender 和 LengthFieldBasedFrameDecoder
                             * 结合新开发的MessagePack 编解码框架，实现对TCP粘包/半包的支持。
                             * 在MessagePack编码器之前，增加LengthFieldPrepender 它将在ByteBuf之前增加2个字节的消息长度字段
                             * 如:
                             * +-----------------+         +---------+--------------+
                             * | "HELLO,WORLD"   | --->    | 0X000C  |"HELLO,WORLD" |
                             * +-----------------+         +---------+--------------+
                             * 在MessagePack解码器之前增加LengthFieldBasedFrameDecoder，用于处理半包消息，这样后面的MessagePack接收到的永远是整包消息，
                             * +---------+--------------+        +-----------------+
                             * | 0X000C  |"HELLO,WORLD" | --->   | "HELLO,WORLD"   |
                             * +---------+--------------+        +-----------------+
                             */
                            ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                            ch.pipeline().addLast("msgpack decoder",new MsgpackDecoder());
                            ch.pipeline().addLast("frameEncoder",new LengthFieldPrepender(2));
                            ch.pipeline().addLast("msgpack encoder",new MsgpackEncoder());
                            ch.pipeline().addLast(new EchoClientHandler(sendNumber));
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();

        }finally {
            //优雅退出，释放线程组资源
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        String host = "127.0.0.1";
        int sendNumber = 10;
        new EchoClient(host,port,sendNumber).run();
    }
}
